<template>
  <div class="annualbox">
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
          <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="用电企业">
                  <FilterSelect2
                      v-model="formdata.companyId"
                      :optionlist="xitonglist"
                      @changeSelect="changeqiye"
                      :valuekey="{ name: 'name', value: 'id' }"
                    ></FilterSelect2>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="日期">
                  <el-date-picker style="width: 100%;" v-model="formdata.yearMonth" type="month" value-format="yyyy-MM" placeholder="选择日期" size="small"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="14" style="text-align: right;">
                <el-form-item label="">
                  <el-button size="small" @click="chongzhi">重 置</el-button>
                  <el-button size="small" type="primary" @click="gettablelist">查 询</el-button>
                </el-form-item>
              </el-col>
          </el-row>
      </el-form>
    </div>
    <div class="bodybox">
        <TopTitle @command="command" @daochu="daochu" @shuaxin="gettablelist">
          <template #leftother>
            <!-- <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-success="handleChange"> -->
              <el-button type="primary" size="small" @click="importDialogVisible=true">工时模板导入</el-button>
            <!-- </el-upload> -->
            <el-button type="primary" size="small" @click="setadd">保 存</el-button>
            <el-button type="primary" size="small" @click="workexport">工时模板导出</el-button>
            <el-button  type="primary" size="small" @click="lastmonth">复制上月数据</el-button>
          </template>
        </TopTitle>
        <div class="table">
          <el-table
            border
            :header-cell-style="{ 'text-align': 'center', background: '#f5f5f5' }"
            v-loading="loading"
            height="calc(100% - 1px)"
            style="width: 100%"
            :size="iissize"
            ref="tabledataref"
            :data="tableData"
            :key="tableKey"
            highlight-current-row
            @current-change="handleCurrentChange"
          >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column
            v-if="tableData.length"
            type="index"
            label="序号"
            width="50">
          </el-table-column>
            <el-table-column v-for="(item) in tableConfig" :key="item.id" :label="item.label" :prop="item.prop" :width="item.width" :min-width="item.minwidth">
              <template #default="{ row }">
                <div v-if="row.isput&&item.label!=='部门'&&item.label!=='班组'"><el-input @change="putinput(row)" v-model="row[item.prop]" size="mini"></el-input></div>
                <div v-else>{{row[item.prop]}}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
    </div>
    <el-dialog
      title="导入年度预算表"
      :visible.sync="importDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="upload"
        :auto-upload="false"
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-change="handleChange"
        accept=".xlsx,.xls"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="small">取 消</el-button>
        <el-button type="primary"  size="small" @click="sure">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import {getBudgetListapi,postImportExcelapi,deleteBudgetListapi} from '@/api/energy-consumption/demand/annual-budget'
import {getHoursTeamapi,postUpdateOneapi,postSetAddapi,getLastMonthapi,postSetImportapi} from '@/api/energy-consumption/demand/hours-team'
import { getCompanyListApi } from '@/api/energy-consumption/Equipment-energy/Energy-analysis'
import TopTooltip from '@/components/TopTitle/newtitle.vue'
import TableColumn from '@/components/Table/index.vue'
import { exportexcel } from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTooltip,
    TableColumn
  },
  data() {
    return {
      formdata:{yearMonth:dayjs().format('YYYY-MM')},
      xitonglist:[],
      iissize: 'medium',
      fileList:[],
      importDialogVisible:false,
      tableData: [],
      formfile:{},
      tableConfig:[],
      loading:false,
      tableKey:0,
      entity:{}
    };
  },

  async mounted() {
    const { data: { list } } = await getCompanyListApi()
    this.xitonglist = list
    const companyId = localStorage.getItem('companyId')
    this.$set(this.formdata,'companyId',companyId?+companyId:list[0].id)
    this.gettablelist()
  },

  methods: {
    // 获取表格数据
    async gettablelist(){
      this.loading=true
      const {data:{entity}}=await getHoursTeamapi({companyId:this.formdata.companyId,yearMonth:this.formdata.yearMonth.replace('-', '')})
      this.entity=entity
      this.tableConfig= [
        { label: '部门', prop: 'departmentName' ,'minwidth':'120'},
        { label: '班组', prop: 'teamName' ,'minwidth':'120'},
        { label: '人员', prop: 'personName' ,'minwidth':'120'},
      ]
      const obj=entity.workingHoursData.find(ele=>ele.workingHoursData)?.workingHoursData
      Object.keys(obj?obj:{}).map(ele=>{
        this.tableConfig.push( {
          label:ele,
          prop:ele
        })
      })
      this.tableData=entity.workingHoursData.map(ele=>{
          return {
            ...ele,
            ...ele.workingHoursData,
            isput:false
          }
       })
      this.loading=false
    },
    cancel(){
      this.importDialogVisible = false
      this.fileList=[]
      this.formfile={}
    },
    // 单选修改
    handleCurrentChange(row){
      this.$refs.tabledataref.setCurrentRow(row)
      if(row){
        this.tableData.forEach(ele=>{
            this.$set(ele, 'isput',ele.id==row.id? true:false)
        })
      }
    },
    // 单条修改
    putinput(row){
      const {departmentId,departmentName,id,isput,personName,teamId,teamName,workingHoursData,...obj}=row
      postUpdateOneapi({departmentId,id,personName,teamId,workingHoursData:obj}).then(res=>{
         this.$message({
              type: res.code == '200' ? 'success' : 'warning',
              message:res.code=='200'?'修改成功':res.message
         })
         this.gettablelist()
      })
    },
    // 全部保存
    setadd(){
      const array=this.tableData.map(ele=>{
        const {departmentId,departmentName,id,isput,personName,teamId,teamName,workingHoursData,...obj}=ele
        return {
           departmentId,id,personName,teamId,workingHoursData:obj
        }
      })
      postSetAddapi({workingHoursData:array,companyId:this.entity.companyId,yearMonth:this.entity.yearMonth}).then(res=>{
         this.$message({
              type: res.code == '200' ? 'success' : 'warning',
              message:res.code=='200'?'保存成功':res.message
         })
         this.gettablelist()
      })
    },
    // 复制上月数据
    async lastmonth(){
      this.loading=true
      const {data:{entity}}=await getLastMonthapi({companyId:this.formdata.companyId,yearMonth:this.formdata.yearMonth.replace('-', '')})
      this.tableConfig= [
        { label: '部门', prop: 'departmentName' ,'minwidth':'120'},
        { label: '班组', prop: 'teamName' ,'minwidth':'120'},
        { label: '人员', prop: 'personName' ,'minwidth':'120'},
      ]
      const obj=entity.workingHoursData.find(ele=>ele.workingHoursData)?.workingHoursData
      Object.keys(obj?obj:{}).map(ele=>{
        this.tableConfig.push( {
          label:ele,
          prop:ele
        })
      })
      const array=entity.workingHoursData.map(ele=>{
          return {
            ...ele,
            ...ele.workingHoursData,
            isput:false
          }
       })
       this.tableData= [...this.tableData, ...array].reduce((acc, current) => {
        const exists = acc.some(item => item.id === current.id);
        if (!exists) {
          acc.push(current);
        }
        return acc;
      }, []);
      this.loading=false
    },
    // 导入
    async handleChange(val,file){
      this.fileList=file
      this.formfile = val.raw
    },
    // 导入
    async sure(val,file){
      // this.loading=false
      const formData = new FormData();
      formData.append('file', this.formfile);
      formData.append('companyId', this.formdata.companyId);
      formData.append('yearMonth', this.formdata.yearMonth.replace('-', ''));
      const res= await postSetImportapi(formData)
      this.$message({
        type:res.code==200?'success':'warning',
        message:res.code==200?'导入成功':res.message
      })
      this.cancel()
      this.tableConfig= [
        { label: '部门', prop: 'departmentName' ,'minwidth':'120'},
        { label: '班组', prop: 'teamName' ,'minwidth':'120'},
        { label: '人员', prop: 'personName' ,'minwidth':'120'},
      ]
      const obj=res.data.list[0]?.workingHoursData.find(ele=>ele.workingHoursData)?.workingHoursData
      Object.keys(obj?obj:{}).map(ele=>{
        this.tableConfig.push( {
          label:ele,
          prop:ele
        })
      })
      this.tableData=res.data.list[0]?.workingHoursData.map(ele=>{
          return {
            ...ele,
            ...ele.workingHoursData,
            isput:false
          }
      })
      // this.loading=false
    },
    chongzhi(){
      const companyId = localStorage.getItem('companyId')
      this.$set(this.formdata,'companyId',companyId?+companyId:this.xitonglist[0].id)
      this.formdata.yearMonth=dayjs().format('YYYY-MM')
      this.gettablelist()
    },
        // 导出
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/team/work/hours/set/export',
        {companyId:this.formdata.companyId,yearMonth:this.formdata.yearMonth.replace('-', '')},
        '班组工时'
      )
    },
    // 工时模板
    workexport(){
      exportexcel(
        '/ecm-microservice-biz/ecm/team/work/hours/set/demo',
        {companyId:this.formdata.companyId,yearMonth:this.formdata.yearMonth.replace('-', '')},
        '工时模板'
      )
    },
    // 表格密度调节
    command(val) {
      this.iissize = val
    },
    changeqiye(val) {
      localStorage.setItem('companyId', val)
      
    },
  },
};
</script>
<style lang="scss" scoped>
.annualbox{
  height: 100%;
  padding: 10px;
  .topbox{
    height: 80px;
    padding: 20px;
    background-color: #fff;
    margin-bottom: 10px;
  }
  .bodybox{
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .table{
      height: 92%;
      .link{
        margin-right: 10px;
      }
    }
  }
}
// ::v-deep .upload-demo{
//   display: inline-block;
//   margin-right: 10px;
// }
// ::v-deep .el-upload-list{
//   display: none;
// }
</style>